package com.netkit.event;

import java.util.Collection;

import com.netkit.NetkitContext;
import com.netkit.Session;
import com.netkit.logger.Logger;

public class HeatbeatListener implements Runnable {
	private static final Logger logger = Logger.getLogger(HeatbeatListener.class.getName());
	private NetkitContext context;

	public HeatbeatListener(NetkitContext context) {
		this.context = context;
	}

	public void run() {
		try {
			Collection<Session> sessions = this.context.getAllSessions();

			for (Session session : sessions) {
				Long heartbeatTime = Long.valueOf(session.getLastCommunicationTime());
				long diffTime = System.currentTimeMillis() - heartbeatTime.longValue();
				if (diffTime > this.context.getSessionTimeout()) {
					logger.warn("the session[" + session.getSessionId() + "] was timeout,close this channel - [" + session.getRemoteAddress() + "]");
					session.close();
				}
			}
		} catch (Exception e) {
			logger.warn(e.getMessage(), e);
		}
	}
}